<?php 

class Tx_IfpCurriculum2_Utility_ObjectStorageSorter {
    protected $property;
    protected $direction;

    public function sortObjectStorage(Tx_Extbase_Persistence_ObjectStorage $objectStorage,$property=null,$direction='ASC') {
        $objectStorage->rewind();
        $sample    = $objectStorage->current();
        $vars    = get_object_vars($sample);
        $getterMethodName = 'get' . ucfirst($property);
        $objectStorageArray = $objectStorage->toArray();
        if (isset($property)) {
        	
            if (method_exists($sample,$getterMethodName)) {
                $this->direction= $direction;
                $this->property = $property;
                usort($objectStorageArray, array($this,'_compare'));
            } else {
                return false;
            }
        } else {
            list($property,$var) = each($sample);
            $this->direction= $direction;
            $this->property    = $property;
            usort($objectStorageArray, array($this,'_compare'));
        }
        if(!empty($objectStorageArray)) {
            $objectStorage = new Tx_Extbase_Persistence_ObjectStorage();
            foreach($objectStorageArray as $object) {
                $objectStorage->attach($object);
            }
        }
        return $objectStorage;
    }

    protected function _compare($apple, $orange) {
        $getterMethodName = 'get' . ucfirst($this->property);
        if (call_user_func_array(array($apple,$getterMethodName), array()) == call_user_func_array(array($orange,$getterMethodName), array())) return 0;
        if ($this->direction == 'ASC')
            return (call_user_func_array(array($apple,$getterMethodName), array()) < call_user_func_array(array($orange,$getterMethodName), array())) ? -1 : 1;
        else
            return (call_user_func_array(array($apple,$getterMethodName), array()) > call_user_func_array(array($orange,$getterMethodName), array())) ? -1 : 1;
    }
}
?>